from django.views.generic import View
from django.http import JsonResponse
from ..models.Literature import Literature
import traceback
import os

class LiterUploadFileView(View):
    def get(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            liter = Literature.objects.get(uuid=id)
            res["code"] = 200
            res["message"] = "查询成功"
            res["data"] = {
                'uuid': str(liter.uuid),
                'title': liter.title,
                'zh_title': liter.zh_title,
                'db_src': liter.db_src,
            }
        except Exception as e:
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)
    
    def post(self, request, id):
        res = {"code": 400, "message": "", "data": None}
        try:
            liter = Literature.objects.get(uuid=id)
            
            uploaded_file = request.FILES.get("file")  # "file" 是前端 formData 中的字段名

            if not uploaded_file:
                res["code"] = 404
                res["message"] = "未检测到上传的文件"
                return JsonResponse(res)
            
            # 获取文件后缀（含点，例如 '.pdf'）
            _, ext = os.path.splitext(uploaded_file.name)
            
            folder_path = os.path.join(".", "literature_resource_files")
            os.makedirs(folder_path, exist_ok=True)  # 自动创建目录
            
            filename = f"{liter.uuid}{ext}"
            file_path = os.path.join(folder_path, filename)
            
            with open(file_path, "wb+") as destination:
                for chunk in uploaded_file.chunks():
                    destination.write(chunk)
                    
            liter.db_src = file_path
            liter.save()
            
            res["code"] = 200
            res["message"] = "文件上传并保存成功"
            res["data"] = None
        except Exception as e:
            traceback.print_exc()
            res["code"] = 500
            res["message"] = "服务器错误：" + str(e)
        return JsonResponse(res)